package com.bazhua.bazo.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bazhua.bazo.common.utils.MD5Util;
import com.bazhua.bazo.common.wxapplet.model.WxAccountResponse;
import com.bazhua.bazo.config.JwtConfig;
import com.bazhua.bazo.repository.entity.WechatUser;
import com.bazhua.bazo.repository.mapper.WechatUserMapper;
import com.bazhua.bazo.repository.model.AdminLogin;
import com.bazhua.bazo.repository.model.AdminUpdatePassword;
import com.bazhua.bazo.repository.model.UserType;
import com.bazhua.bazo.repository.model.WxUserSearch;
import com.bazhua.bazo.repository.model.result.BaseResultCode;
import com.bazhua.bazo.repository.model.result.CommonResult;
import com.bazhua.bazo.repository.model.result.PageListResult;
import com.bazhua.bazo.repository.model.result.ResultUtils;
import com.bazhua.bazo.service.ICheckUserService;
import com.bazhua.bazo.service.IShopInfoService;
import com.bazhua.bazo.service.IWechatUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.util.Date;

/**
 * @Author: starmile
 * @Description:
 * @Create: 2021-01-21 0:50
 **/
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Resource
    private JwtConfig jwtConfig;

    @Value("${admin.username}")
    private String adminUsername;

    @Value("${admin.password}")
    private String adminPassword;

    public WechatUser register(WxAccountResponse wxAccountResponse) {
        return registerUser(wxAccountResponse, UserType.User);
    }

    private WechatUser registerUser(WxAccountResponse wxAccountResponse, Integer userType) {
        WechatUser wechatUser = new WechatUser();
        wechatUser.setCreateTime(new Date());
        wechatUser.setHeadUrl(wxAccountResponse.getUrl());
        wechatUser.setOpenId(wxAccountResponse.getOpenid());
        wechatUser.setUserName(wxAccountResponse.getNickName());
        wechatUser.setUserType(userType);
        baseMapper.insert(wechatUser);
        return wechatUser;
    }

    public WechatUser updateUser(WechatUser wechatUser, WxAccountResponse wxAccountResponse) {
        wechatUser.setCreateTime(new Date());
        wechatUser.setHeadUrl(wxAccountResponse.getUrl());
        wechatUser.setOpenId(wxAccountResponse.getOpenid());
        wechatUser.setUserName(wxAccountResponse.getNickName());
        baseMapper.updateById(wechatUser);
        return wechatUser;
    }

    public WechatUser findByOpenId(String openId) {
        QueryWrapper<WechatUser> wrapper = new QueryWrapper();
        wrapper.eq("open_id", openId);
        WechatUser wechatUser = baseMapper.selectOne(wrapper);
        return wechatUser;
    }

    public WechatUser findById(Long id) {
        QueryWrapper<WechatUser> wrapper = new QueryWrapper();
        wrapper.eq("id", id);
        WechatUser wechatUser = baseMapper.selectOne(wrapper);
        return wechatUser;
    }

    public WechatUser updatePhone(String openId, String phone) {
        WechatUser wechatUser = findByOpenId(openId);
        wechatUser.setPhone(phone);
        baseMapper.updateById(wechatUser);
        return wechatUser;
    }

    public CommonResult updatePassword(AdminUpdatePassword adminUpdatePassword) {
        WechatUser wechatUser = baseMapper.selectById(adminUpdatePassword.getUserId());
        wechatUser.setPassword(MD5Util.encrypt(adminUpdatePassword.getPassword()));
        baseMapper.updateById(wechatUser);
        return ResultUtils.ok();
    }

    public CommonResult login(AdminLogin adminLogin) {
        if (adminLogin.getPhone().equals(adminUsername) && adminLogin.getPassword().equals(adminPassword)) {
            String token = jwtConfig.createTokenByAdmin(0l, adminLogin);
            return ResultUtils.ok(token);
        }
        QueryWrapper<WechatUser> wrapper = new QueryWrapper();
        wrapper.eq("phone", adminLogin.getPhone());
        wrapper.eq("password", MD5Util.encrypt(adminLogin.getPassword()));
        WechatUser wechatUser = baseMapper.selectOne(wrapper);

        if (wechatUser == null) {
            return ResultUtils.error(BaseResultCode.USER_PASSWORD_ERROR);
        }
        String token = jwtConfig.createTokenByAdmin(wechatUser.getId(), adminLogin);
        return ResultUtils.ok(token);
    }

    public PageListResult page(WxUserSearch wxUserSearch) {
        QueryWrapper<WechatUser> wrapper = new QueryWrapper<>();
        if (!StringUtils.isBlank(wxUserSearch.getWxUserName())) {
            wrapper.eq("user_name", wxUserSearch.getWxUserName());
        }
        if (!StringUtils.isBlank(wxUserSearch.getPhone())) {
            wrapper.eq("phone", wxUserSearch.getPhone());
        }
        if (wxUserSearch.getUserType() != null) {
            wrapper.eq("user_type", wxUserSearch.getUserType());
        }
        Page<WechatUser> page = new Page<>(wxUserSearch.getPageNum(), wxUserSearch.getPageSize());
        page = baseMapper.selectPage(page, wrapper);
        return ResultUtils.pageOk(page);
    }

    public CommonResult setAgent(Long userId) {
        WechatUser wechatUser = findById(userId);
        wechatUser.setUserType(UserType.Agent);
        baseMapper.updateById(wechatUser);
        return ResultUtils.ok();
    }

    public CommonResult setAdmin(Long userId) {
        WechatUser wechatUser = findById(userId);
        wechatUser.setUserType(UserType.Manage_User);
        baseMapper.updateById(wechatUser);
        return ResultUtils.ok();
    }

    public CommonResult setUser(Long userId) {
        WechatUser wechatUser = findById(userId);
        wechatUser.setUserType(UserType.User);
        baseMapper.updateById(wechatUser);
        return ResultUtils.ok();
    }
}
